﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ICeFramework.DataAccess.Enums;
using ICeFramework.DataAccess.SettingsStorage;
using ICeFramework.DataAccess.Interfaces;
using ICeFramework.DataAccess.SqlConnections;
using ICeFramework.Common.DataLayer.Enums;

namespace ICeFramework.Win.UI
{
    public partial class SqlConnectionDialog : Form
    {
        private ServerType _type;
        private string _connectionString = string.Empty;
        private string _connectionName = string.Empty;
        private bool _connectionSuccess;
        
        private SqlDataStorageEntity _settings = new SqlDataStorageEntity();
        #region public SqlDataStorageEntity Settings
        /// <summary>
        /// Get/Sets the Settings of the SqlConnectionDialog
        /// </summary>
        /// <value></value>
        public SqlDataStorageEntity Settings
        {
            get { return _settings; }
            set { _settings = value; }
        }
        #endregion

        #region public string ConnectionString
        /// <summary>
        /// Gets the ConnectionString of the SqlConnectionDialog
        /// </summary>
        /// <value></value>
        public string ConnectionString
        {
            get { return _connectionString; }
        }
        #endregion

        #region public ServerType ServerType
        /// <summary>
        /// Get/Sets the ServerType of the SqlConnectionDialog
        /// </summary>
        /// <value></value>
        public ServerType ServerType
        {
            get { return _type; }
            private set
            {
                if (value == ServerType.MsSql)
                {
                    comboBox1.SelectedIndex = 0;
                }
                else
                {
                    comboBox1.SelectedIndex = 1;
                }
                _type = value;
            }
        }
        #endregion

        private ISqlConnection _connection;
        public ISqlConnection Connection
        {
            get { return _connection; }
        }

        #region public SqlConnectionDialog(string connectionName)
        /// <summary>
        /// Initializes a new instance of the <b>SqlConnectionDialog</b> class.
        /// </summary>
        public SqlConnectionDialog(string connectionName)
        {
            InitializeComponent();
            _connectionName = connectionName;
        }
        #endregion

        #region private void chkTrusted_CheckedChanged(object sender, EventArgs e)
        /// <summary>
        /// This method is called when the chkTrusted's CheckedChanged event has been fired.
        /// </summary>
        /// <param name="sender">The <see cref="object"/> that fired the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> of the event.</param>
        private void chkTrusted_CheckedChanged(object sender, EventArgs e)
        {
            txtUser.Enabled = !chkTrusted.Checked;
            txtPassword.Enabled = !chkTrusted.Checked;
        }
        #endregion

        #region public bool GetDialog(bool connectAutomatically)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="connectAutomatically"></param>
        /// <returns></returns>
        public bool GetDialog(bool connectAutomatically)
        {
            GetConnectionString();
            if (!connectAutomatically)
            {
                return this.ShowDialog() == DialogResult.OK;
            }
            else
            {
                TestConnection(true);
                if (!_connectionSuccess)
                {
                    return this.ShowDialog() == DialogResult.OK;
                }
                else
                {
                    return true;
                }
            }
        }
        #endregion

        #region private void GetConnectionString()
        /// <summary>
        /// 
        /// </summary>
        private void GetConnectionString()
        {
            _settings = SqlDataStorage.Load(_connectionName);
            if (_settings == null)
            {
                _settings = new SqlDataStorageEntity();
            }
            _connectionString = _settings.ConnectionString;
            ServerType = _settings.ServerType;
            txtServer.Text = _settings.Server;
            txtPort.Text = _settings.Port.ToString();
            txtDatabase.Text = _settings.Database;
            txtUser.Text = _settings.UserName;
            txtPassword.Text = _settings.Password;
            chkTrusted.Checked = _settings.TrustedConnection;
        }
        #endregion

        #region private void SetSettings()
        /// <summary>
        /// 
        /// </summary>
        private void SetSettings()
        {
            _settings.ServerType = ServerType;
            _settings.Server = txtServer.Text;
            _settings.Port = txtPort.Text;
            _settings.Database = txtDatabase.Text;
            _settings.UserName = txtUser.Text;
            _settings.Password = txtPassword.Text;
            _settings.TrustedConnection = chkTrusted.Checked;
            SqlDataStorage.Save(_connectionName, _settings);
        }
        #endregion

        #region private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        /// <summary>
        /// This method is called when the comboBox1's SelectedIndexChanged event has been fired.
        /// </summary>
        /// <param name="sender">The <see cref="object"/> that fired the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> of the event.</param>
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtPort.Enabled = comboBox1.SelectedIndex == 1;
            chkTrusted.Enabled = comboBox1.SelectedIndex == 0;
            if (comboBox1.SelectedIndex == 1)
            {
                txtUser.Enabled = !chkTrusted.Enabled;
                txtPassword.Enabled = !chkTrusted.Enabled;
                _type = ServerType.MySql;
            }
            else
            {
                txtUser.Enabled = !chkTrusted.Checked;
                txtPassword.Enabled = !chkTrusted.Checked;
                _type = ServerType.MsSql;
            }
        }
        #endregion

        #region private void btnTest_Click(object sender, EventArgs e)
        /// <summary>
        /// This method is called when the btnTest's Click event has been fired.
        /// </summary>
        /// <param name="sender">The <see cref="object"/> that fired the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> of the event.</param>
        private void btnTest_Click(object sender, EventArgs e)
        {
            TestConnection(false);
        }
        #endregion

        #region private bool TestConnection(bool silent)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="silent"></param>
        /// <returns></returns>
        private bool TestConnection(bool silent)
        {
            if (string.IsNullOrEmpty(txtServer.Text))
            {
                return false;
            }
            SetSettings();
            _connectionSuccess = true;
            _connection = null;
            try
            {
                try
                {
                    switch (_type)
                    {
                        case ServerType.MsSql:
                            _connection = new MSSqlServerConnection(_settings.ConnectionString, _settings.Server, _settings.UserName, _settings.Password);
                            break;
                        case ServerType.MySql:
                            _connection = new MySqlServerConnection(_settings.ConnectionString, _settings.Server, _settings.UserName, _settings.Password);
                            break;
                    }
                    if (!silent)
                    {
                        MessageBox.Show(string.Format("Succesfully connected to {0}", _settings.Server));
                    }
                }
                catch (Exception ex)
                {
                    _connectionSuccess = false;
                    MessageBox.Show(ex.Message, "Error Connecting to Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            finally
            {
                if (_connection != null)
                {
                    _connection.Close();
                }
            }
            return _connectionSuccess;
        }
        #endregion

        #region private void btnOk_Click(object sender, EventArgs e)
        /// <summary>
        /// This method is called when the btnOk's Click event has been fired.
        /// </summary>
        /// <param name="sender">The <see cref="object"/> that fired the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> of the event.</param>
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (TestConnection(true))
            {
                _connectionString = _settings.ConnectionString;
                this.DialogResult = DialogResult.OK;
                Hide();
            }
        }
        #endregion
    }
}
